package org.jeeasy.common.core.tools;

import cn.hutool.core.date.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.jeeasy.common.core.exception.JeeasyException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;


@Log4j2
public class ApplicationUtil {
    public static void printAppInfo(ConfigurableApplicationContext application) {
        Environment env = application.getEnvironment();
        //String ip = InetAddress.getLocalHost().getHostAddress();
        String ip = getIpAddress();
        String port = env.getProperty("server.port");
        String path = env.getProperty("server.servlet.context-path");
        String appName = env.getProperty("spring.application.name", "Jeeasy");
        String activeProfile = env.getProperty("spring.profiles.active");

        path = StringUtils.isBlank(path) ? "" : path;

        String appInfo = """
                \n----------------------------------------------------------
                    Application %s is running!
                    Env: %s
                    StartTime: %s
                    Access URLs:
                        Local: 		http://localhost:%s/
                        External: 	http://%s:%s/
                        Doc文档:     http://%s:%s/doc.html
                ----------------------------------------------------------
                """.formatted(appName, activeProfile, DateUtil.now(), port + path, ip, port + path, ip, port + path);
        log.info(appInfo);
    }

    private static String getIpAddress() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface ni : Collections.list(networkInterfaces)) {
                if (!ni.isLoopback() && !ni.isVirtual()) {
                    Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                    for (InetAddress ia : Collections.list(inetAddresses)) {
                        if (ia.isSiteLocalAddress() && !ia.isLinkLocalAddress()) {
                            return ia.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            throw new JeeasyException("Unable to determine IP address");
        }
        throw new JeeasyException("No real IP address found");
    }
}
